package cn.com.wxd.service.freemarker.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.common.DateUtil;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 * FreeMarker非文件形式的转换
 *
 * @author wangxudong
 */
public class FreeMarkerNoFile {
    private static final Logger log = LoggerFactory.getLogger(FreeMarkerNoFile.class);

    /**
     * 将模板数据进行转换
     *
     * @param templateStr
     * @param data
     *
     * @return
     */
    public String process(String templateStr, HashMap<String, String> data) {
        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String name = DateUtil.getTimestamp();
        stringLoader.putTemplate(name, templateStr);
        cfg.setTemplateLoader(stringLoader);
        try {
            freemarker.template.Template template = cfg.getTemplate(name, "utf-8");

            StringWriter writer = new StringWriter();
            try {
                template.process(data, writer);
                return writer.toString();
            } catch (TemplateException e) {
                log.error("", e);
            }
            return null;
        } catch (IOException e) {
            log.error("", e);
        }
        return null;
    }

    /**
     * 将模板数据进行转换并输出到一个文件
     *
     * @param templateStr
     * @param data
     *
     * @return
     *
     * @throws IOException
     */
    public void processToFile(String templateStr, HashMap<String, String> data, String filePath) throws IOException {
        String str = process(templateStr, data);
        File f = new File(filePath);
        FileOutputStream out2 = null;
        try {
            if (str == null) {
                str = "";
            }
            byte[] buff;
            buff = str.getBytes();
            if (f.isDirectory()) {
                filePath += "/" + DateUtil.getTimestamp() + ".txt";
            } else {
                if (f.exists()) {
                    f.createNewFile();
                }
            }
            out2 = new FileOutputStream(filePath);
            out2.write(buff, 0, buff.length);
        } catch (IOException e) {
            log.error("模板处理错误" + e.getMessage(), e);
            throw e;
        } finally {
            out2.close();
        }
    }
}
